
#include <QImageReader>
#include <QMutexLocker>

#include "ImageThumbnailThread.h"

ImageThumbnailThread::ImageThumbnailThread(const QSize& aSize, QObject* parent)
    : QThread(parent), iSize(aSize), iThreadCancelled(false)
{
}

ImageThumbnailThread::~ImageThumbnailThread()
{
}

void ImageThumbnailThread::run()
{
    QMutexLocker lock(&iMutex);
    
    while (!iThreadCancelled) {
        // Mutex always locked here
        
        if(iImageList.empty()) {
            iWaitCond.wait(&iMutex);
        } else {
            FileInfo info = iImageList.takeFirst();
            lock.unlock();
            
            QImage const image = CreateImage(info);
            emit ThumbnailCreated(info.second, image);
            
            lock.relock();
        }
    }
}

QImage const ImageThumbnailThread::CreateImage(FileInfo const & info) {
    QImageReader reader;
    reader.setFileName(info.first);
    
    QSize imageSize = reader.size();
    imageSize.scale(iSize, Qt::KeepAspectRatio);
    reader.setScaledSize(imageSize);
    
    return reader.read();
}

void ImageThumbnailThread::Cancel()
{
    iThreadCancelled = true;
    iWaitCond.wakeOne();
}

void ImageThumbnailThread::AddImage(QString aFilename, void * requester)
{
    iMutex.lock();
    iImageList.append(FileInfo(aFilename, requester));
    iMutex.unlock();
    iWaitCond.wakeOne();
}
